package dbgroup02.validator;

import java.util.regex.Pattern;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import dbgroup02.bean.Seats;

public class SeatSelectionValidator implements Validator {

	@Override
	public boolean supports(Class clazz) {
		return Seats.class.isAssignableFrom(clazz);
	}
	
	private void validateSeatNumber(String seatNumber, String field, Errors errs) {
		if (seatNumber != null) {
			if (seatNumber.length() == 0) 
				errs.rejectValue(field, field + ".missing", null, "Seat number cannot be empty");
			else if (!Pattern.matches("[0-4]?[0-9][A-Ia-i]", seatNumber)) {
				errs.rejectValue(field, field + ".invalid", null, "Invalid seat number");
			}
		}		
	}

	@Override
	public void validate(Object obj, Errors errs) {
		Seats seats = (Seats) obj;
		
		validateSeatNumber(seats.getSeatNumber1(), "seatNumber1", errs);
		validateSeatNumber(seats.getSeatNumber2(), "seatNumber2", errs);
		validateSeatNumber(seats.getSeatNumber3(), "seatNumber3", errs);
		validateSeatNumber(seats.getSeatNumber4(), "seatNumber4", errs);
		validateSeatNumber(seats.getSeatNumber5(), "seatNumber5", errs);
	}	
}
